package com.hzf.booklibrary.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.zxing.WriterException;
import com.hzf.booklibrary.R;
import com.hzf.booklibrary.base.BaseActivity;
import com.hzf.booklibrary.bean.book.Book;
import com.hzf.booklibrary.bean.support.DownloadBookFailed;
import com.hzf.booklibrary.biz.ImageLoader;
import com.hzf.booklibrary.component.AppComponent;
import com.hzf.booklibrary.component.DaggerMainComponent;
import com.hzf.booklibrary.utils.DownloadUtils;
import com.hzf.booklibrary.utils.FileUtils;
import com.hzf.booklibrary.utils.QRCodeUtils;
import com.hzf.booklibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/9.
 */

public class BookDetailActivity extends BaseActivity implements DownloadUtils.DownloadBookState {
    public static final String BOOK ="book";
    public static void startActivity(Context context, Book books){
        Bundle bundle = new Bundle();
        bundle.putSerializable(BOOK,books);
        Intent intent = new Intent(context,BookDetailActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
    @Bind(R.id.tv_book_name)
    TextView tvName;
    @Bind(R.id.tv_author)
    TextView tvAuthor;
    @Bind(R.id.tv_update_date)
    TextView tvUpdateDate;
    @Bind(R.id.iv_cover)
    ImageView ivCover;
    @Bind(R.id.tv_cover_name)
    TextView tvCoverName;
    @Bind(R.id.iv_qrcode)
    ImageView ivQrCode;
    @Bind(R.id.tv_book_intro)
    TextView tvIntro;

    private Book book;

    private DownloadUtils downloadUtils;


    @Override
    public int getLayoutId() {
        return R.layout.activity_book_detail;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMainComponent.builder()
                .appComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void initTitleBar() {
        mBtnLeft.setText("返回");
        mBtnLeft.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.img_back_left),null,null,null);
        mBtnRight.setVisibility(View.GONE);
        tvCenter.setBackgroundResource(R.drawable.img_book_detail);
    }
    @OnClick(R.id.btn_left)
    public void onClickBack(){
        finish();
    }
    @Override
    public void initDatas() {
        book = (Book) getIntent().getExtras().getSerializable(BOOK);
        downloadUtils = new DownloadUtils(this);
    //  downloadUtils=new DownloadUtils(this, SharedPreferencesUtil.getInstance().getString("ip","192.168.1.222"),22,"root","bFUgqNnqOyFrEYJ4vpWAmXg7y20D");
        EventBus.getDefault().register(this);
    }

    @Override
    public void configViews() {
        hideStatusBar();
        tvName.setText(book.name);
        tvAuthor.setText(book.author.equals("")?"无":book.author);
        if (StringUtils.isEmpty(book.content)){
            tvIntro.setText("无");
        }else {
            tvIntro.setText(book.content);
        }
//        tvIntro.setText(book.content.equals("")|| book.content == null?"\u3000\u3000"+"无":"\u3000\u3000"+book.content);
        tvUpdateDate.setText(book.updatetime.equals("")?"无":book.updatetime);

        if(!book.icon_path.equals("")){//确保有封面
            String path = book.icon_path;
            LogUtils.i("接收到的图书封面Url==:"+path);
            ImageLoader.getInstance(4, ImageLoader.Type.LIFO,ImageLoader.NO_CROP,this)
                    .loadImage(path,ivCover,true);
        }else {//无封面
            tvCoverName.setText(book.name);
            if(book.filetype.equals("txt")||book.filetype.equals("TXT")){//txt
                ivCover.setImageResource(R.drawable.book_txt_bg);
            }else if(book.filetype.equals("pdf")||book.filetype.equals("PDF")){//pdf
                ivCover.setImageResource(R.drawable.book_pdf_bg);
            }else {
                ivCover.setImageResource(R.drawable.book_txt_bg);
            }
        }
        ImageLoader.getInstance(4, ImageLoader.Type.LIFO,ImageLoader.NO_CROP,this).setOnLoadImageFailedListener(new ImageLoader.OnLoadImageFailedListener() {
            @Override
            public void onLoadImageFailed(String tag,ImageView imageView) {
                tvCoverName.setText(book.name);
                imageView.setImageResource(R.drawable.book_txt_bg);
            }
        });
        Bitmap bitmap= null;
        try {
           // String content = Constant.API_BASE_URL+"release/Release_getUrl.do?id="+ book.id;
//            public String author;//图书作者
//            public String icon_path ="";//封面路径
//            public String localIconPath;//本地封面路径
//            public int mark;
//            public String id;//图书id
//            public String name;//图书名称
//            public String type;//图书类型
//            public String url = "";//图书路径
//            public String content = "";//图书简介
//            public String updateTime = "";//更新日期
//            public boolean isSelected = false;
//            public boolean isFromSD = true;
//            public int chaptersCount=1;

            String content = "id:"+ book.id+",author:"+book.author+",img:"+book.icon_path+",name:"+book.name
                    +",type:"+book.filetype+",path:"+book.path+",ut:"+book.updatetime+",sd:"+book.isFromSD+",cn:"+book.chaptersCount;
//            String content = Constant.API_BASE_URL+"Book/cloud/httpCommandService?cmd=books&cmd_op=booksgetUrl&bookId="+book.id;
//            if(DeviceUtils.isXiaoPai(this)){
//                content = Constant.API_BASE_URL+"Book/cloud/httpCommandService?cmd=books&cmd_op=sBooksgetUrl&bookId="+book.id;
//            }



            bitmap = QRCodeUtils.Create2DCode(content,
                    (int)getResources().getDimension(R.dimen.dimen_79dp),
                    (int)getResources().getDimension(R.dimen.dimen_79dp));
        } catch (WriterException e) {
            e.printStackTrace();
        }

        bitmap = QRCodeUtils.addLogoToQrCode(bitmap, BitmapFactory.decodeResource(getResources(),R.drawable.img_qrcode_logo));
        ivQrCode.setImageBitmap(bitmap);

    }
   @OnClick(R.id.btn_read)
    public void onClickRead(){
       showDialog();
       if("".equals(book.path)){
           ToastUtils.showSingleLongToast("服务器无该图书资源");
           return;
       }
       downloadUtils.downloadBooks(book);
    // downloadUtils.downloadFileByFTP(book);
   }

    @Override
    public void downLoading(long currentLength,long totalLength) {

    }

    @Override
    public void downloadSuccess(long currentLength,long totalLength) {
        dismissDialog();
        if(book.filetype.equals("txt")||book.filetype.equals("TXT")){//阅读txt
            ReadActivity.startActivity(this, book, book.isFromSD);
        }else if(book.filetype.equals("pdf")||book.filetype.equals("PDF")){//阅读pdf
            PDFReadActivity.start(this,FileUtils.getPdfFile(book.id,book.chaptersCount),book.name);
        }else {
            ToastUtils.showSingleLongToast("图书不存在，请联系管理员！！！");
        }
    }
    @Override
    public void downloadFailed() {
        dismissDialog();
        EventBus.getDefault().post(new DownloadBookFailed());//下载图书失败
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downloadBookFailed(DownloadBookFailed downloadBookFailed){
        ToastUtils.showSingleToast("下载图书失败，请检查网络或图书资源");
    }
}
